package storage

import (
	"database/sql"
	"github.com/jmoiron/sqlx"
	"time"
	"web_framework/model"
)

const (
	RedisRouterTaskGoingSetKey   = ":task:queue:going"   //进行中（正在下载，暂停，等待）的任务有序集合
	RedisRouterTaskLoadIngSetKey = ":task:queue:loading" //正在下载的任务有序集合
	RedisRouterTaskWaitingSetKey = ":task:queue:waiting" //等待中的任务队列
	RedisRouterTaskInfoKey       = ":task:info"    //路由器任务详情
	RedisRouterTaskVerKey        = ":task:taskVer" //路由器任务版本号信息
	RedisRouterActualSpeedKey    = ":actualSpeed"  //路由器实时速度

	RouterTaskLoadingMax = 3 //最大允许同时下载的任务数
	RouterTaskWaitingMax = 3 //最大允许等待下载的任务数

	DoneListPer = 2 //已完成列表没页展示的条数
)

//CreateTask 添加任务至数据库
func CreateTask(db sqlx.Execer, data model.Task) (sql.Result, error) {
	// var res model.Router
	l, _ := time.LoadLocation("Asia/Shanghai")
	timeNow := time.Now().In(l)
	result, err := db.Exec("insert into device_download_task(device_id, file_url, res_name,status,create_time) value(? , ? , ? , ? , ?)", data.DeviceID, data.URL, data.ResName, model.TaskStatusloading, timeNow)
	if err != nil {
		return nil, err
	}
	return result, nil
}

//UpdateTaskInfo  修改数据库
func UpdateTaskInfo(db sqlx.Execer, taskId int64, data model.Task) (sql.Result, error) {
	// var res model.Router
	result, err := db.Exec("update device_download_task set total_size = ? ,path = ? ,status = ?,complete_time = ? where task_id = ?", data.TotalSize, data.Path, data.Status, data.CompleteTime, taskId)
	if err != nil {
		return nil, err
	}
	return result, nil
}

func GetTask(db sqlx.Queryer, deviceId int, taskStatus int, page int) ([]model.Task, error) {
	var res []model.Task
	start := (page - 1) * DoneListPer
	err := sqlx.Select(db, &res, "select * from device_download_task where device_id = ? and status = ? limit ?,?", deviceId, taskStatus, start, DoneListPer)
	if err != nil {
		return res, err
	}

	return res, nil
}
